package com.example.interceptor;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2019/3/18
 * @Description: 类描述
 **/
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String path = request.getRequestURI();
        try (Entry entry = SphU.entry(path)) {
            System.out.println("API正常访问");
        } catch (BlockException ex) {
            response.setCharacterEncoding("utf-8");
            PrintWriter printWriter = response.getWriter();
            response.setStatus(429);
            printWriter.write("{\"result\":\"API访问次数超限!\"}");
            response.setContentType("text/html;charset=utf-8");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
